import React, { useState, useRef } from 'react';

const scrollToAnchor = (index: number, smooth: boolean) => {
    const sectionEle = document.querySelectorAll('#wxrc-section div[class="content-box"]');
    if (sectionEle) {
        sectionEle[index].scrollIntoView({ block: 'start', behavior: smooth ? 'smooth' : 'auto' });
    }
};

const useAsideNav = () => {
    const sectionRef: any = useRef();
    const [navList, setNavList] = useState([]);
    const initNav = () => {
        const content = sectionRef?.current.querySelectorAll('div[class="content-box"]');
        const newNavList = [];
        content.forEach((item, index) => {
            if (item.getElementsByTagName('h2').length !== 0) {
                newNavList.push(`[${index}]-` + item.getElementsByTagName('h2')[0].innerHTML);
            }
        });
        setNavList(newNavList);
    };

    const AsideNav = () => {
        return (
            <div>
                {navList.map((item, index) => {
                    return (
                        <a onClick={scrollToAnchor.bind(null, index, true)} key={index + ''}>
                            {item}
                        </a>
                    );
                })}
            </div>
        );
    };

    return { navList, setNavList, sectionRef, initNav, AsideNav };
};

export default useAsideNav;
